package com.framework.spring.scan.util;

import com.framework.spring.scan.bean.A;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j(topic = "e")
public class MyScanner {

	private File path = new File(A.class.getResource("/").getPath());

	public List<String> listName = new ArrayList<>();

	public Map<String, AbstractBeanDefinition> map = new HashMap<>();

	/**
	 * 模拟spring完成扫描符合规则类
	 * @param packageName
	 * @throws ClassNotFoundException
	 */
	public void scan(String packageName) throws ClassNotFoundException {
		String rootPath = path.getPath();
		String scanPath = packageName.replaceAll("\\.", "\\\\");

		rootPath = rootPath + File.separator + scanPath;

		File rootDir = new File(rootPath);
		String[] files = rootDir.list();
		for (String file : files) {
			String name = file.replaceAll(".class", "");
			String beanName = name.toLowerCase();
			String fileName = packageName.concat(".").concat(name);
			Class<?> clazz = Class.forName(fileName);
			if (clazz.isAnnotationPresent(Component.class)) {
				GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
				beanDefinition.setBeanClass(clazz);
				if (clazz.isAnnotationPresent(Scope.class)) {
					beanDefinition.setScope(clazz.getAnnotation(Scope.class).value());
				}
				map.put(beanName, beanDefinition);
				listName.add(beanName);
			}
		}

	}

	public List<String> getListName() {
		return listName;
	}

	public void setListName(List<String> listName) {
		this.listName = listName;
	}

	public Map<String, AbstractBeanDefinition> getMap() {
		return map;
	}

	public void setMap(Map<String, AbstractBeanDefinition> map) {
		this.map = map;
	}
}
